package com.yangluyao.test.copywriter;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author YLY
 * @ClassName ContainerNotSafeDemo
 * @Date 2020/4/30
 * @Version 1.0.2
 */
public class ContainerNotSafeDemo {
    public static void main(String[] args) {
        /**
         * 1、Collections.synchronizedMap(new HashMap<>())
         * 2、new ConcurrentHashMap<>()
         */
        Map<String, String> map = new ConcurrentHashMap<>();
        for (int i = 0; i <300 ; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,8));
                System.out.println(map);
            },String.valueOf(i)).start();
        }
    }

    /**
     * set线程不安全即解决方案
     */
    private static void setNotSafe() {
        Set<String> set = new CopyOnWriteArraySet<>();  //Collections.synchronizedSet(new HashSet<>())
        for (int i = 0; i <300 ; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
        new HashSet<>().add("a");
    }

    /**
     * list线程不安全即解决方案
     */
    private static void listNotSafe() {
        List<String> list = new CopyOnWriteArrayList<>(); //Collections.synchronizedList(new ArrayList<>())
        for (int i = 0; i <300 ; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }

}
